package common

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// 定义手机号正则表达式
var regex = regexp.MustCompile(`^1[3456789]\d{9}$`)
var idCardRegex = regexp.MustCompile(`(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)`)

// CheckPhone 检查手机号是否合法
func CheckPhone(phone string) bool {
	return regex.MatchString(phone)
}

// ContainString 判断目标字符串是否存在于字符串切片中
func ContainString(slice []string, target string) bool {
	for _, v := range slice {
		if v == target {
			return true
		}
	}
	return false
}

func IsIDNumber(val interface{}) bool {
	value, ok := val.(string)
	if !ok {
		return false
	}
	value = strings.ToUpper(strings.TrimSpace(value))
	// 18位长检测
	if len(value) != 18 {
		return false
	}
	// 加权因子
	weightFactor := [...]int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
	// 校验码
	checkCode := [...]byte{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}
	last := value[17]
	num := 0
	for i := 0; i < 17; i++ {
		tmp, err := strconv.Atoi(string(value[i]))
		if err != nil {
			return false
		}
		num = num + tmp*weightFactor[i]
	}
	resisue := num % 11
	if checkCode[resisue] != last {
		return false
	}

	return idCardRegex.MatchString(value)
}

func ParseUint32Slice(s string) ([]uint32, error) {
	var result []uint32
	if s == "" {
		return result, nil // 空字符串返回空切片
	}

	parts := strings.Split(s, ",")
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		num, err := strconv.ParseUint(part, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("invalid number %q: %w", part, err)
		}
		result = append(result, uint32(num))
	}

	return result, nil
}

func ParseIntSlice(s string) ([]int, error) {
	var result []int
	if s == "" {
		return result, nil // 空字符串返回空切片
	}

	parts := strings.Split(s, ",")
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		num, err := strconv.ParseUint(part, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("invalid number %q: %w", part, err)
		}
		result = append(result, int(num))
	}

	return result, nil
}
